package com.gitee.yusugar.auth;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.yusugar.core.coder.RSACoder;

import java.util.HashMap;
import java.util.Map;

public class AuthUtil {

    private static final Map<String, byte[]> PRIVATE_KEY_MAP = new HashMap<>();

    /**
     * 初始化 公钥和私钥，并返回公钥
     *
     * @return 公钥
     */
    public static PublicKeyInfo initKeyObtainPublicKey() {
        try {
            Map<String, Object> keyMap = RSACoder.initKey();

            // 生成Key
            String key;
            do {
                key = IdUtil.simpleUUID();
            } while ( PRIVATE_KEY_MAP.get( key ) != null );

            // 存储私钥
            PRIVATE_KEY_MAP.put( key, RSACoder.getPrivateKey( keyMap ) );

            // 构建密钥对象, 并返回
            PublicKeyInfo publicKeyInfo = new PublicKeyInfo();
            publicKeyInfo.setKey( key ).setPublicKey( Base64.encode( RSACoder.getPublicKey( keyMap ) ) );
            return publicKeyInfo;
        } catch ( Exception e ) {
            return null;
        }
    }

    /**
     * 用私钥解密密文
     *
     * @param cipherInfo 密文信息
     * @return 原文
     */
    public static String decryptByPrivateKey( CipherInfo cipherInfo ) {
        try {

            // 解析参数
            String key = cipherInfo.getKey();
            if ( StrUtil.isBlank( key ) )
                return null;
            else {
                String cipher = cipherInfo.getCipher();
                if ( StrUtil.isBlank( cipher ) )
                    return null;
                else {
                    // 获取私钥
                    byte[] privateKey = PRIVATE_KEY_MAP.get( key );

                    if ( privateKey == null )
                        return null;
                    // 删除私钥
                    PRIVATE_KEY_MAP.remove( key );
                    // 返回原文
                    return new String( RSACoder.decryptByPrivateKey( Base64.decode( cipher ), privateKey ) );
                }
            }
        } catch ( Exception e ) {
            return null;
        }
    }
}
